% function to detrend, de-bias, calibrate, fft, and cross & auto power calculation
% latest date 30.10.2002

function[SPMatrix] = GetTwoSpectra(TS,ProcDef),

sensor = ProcDef.sensor;
Notchi = TS.filter.NotchF(2:5,:);		% NOTE ! there may be problems 
IsNotch = TS.filter.Filt(2:5,:);		%        if notch do not have right dimension..
oi = size(Notchi);
if oi(2) == 1,
notch = Notchi(find(IsNotch)); 
elseif oi(2) == 2,
   [x,y]=find(IsNotch);
   notch = Notchi(1:oi(2),1:oi(2));
end;
hpb1 = TS.filter.Filt(1);			% NOTE ! high pass filter is always disabled
prob = TS.probe.dist;	% 	 in calib05.m
gain = TS.probe.gain;
nband = TS.head.band;
nchannel = TS.head.nchannel;
block = ProcDef.block;
len = ProcDef.len;
TLine1 = ProcDef.TLine1;
TLRad1 = ProcDef.TLRad1;
TLFreq1 = ProcDef.TLFreq1;
nfrq=ProcDef.nfrq;
notchdef = ProcDef.notchdef;
Array = ProcDef.Array;

disp('GetTwoSpectra -> Computing calibration table');

for i = 1:nchannel,
   nt=find(notch(:,notchdef(i)));
   if length(nt)>0,
      nt=notch(nt);
   end;
   [cplx,frq1] = calib05(sensor(i),nband,block,prob(i),nt,hpb1,gain(i));
     
CalData(i,:) = cplx;
end;

%------------native declarations---------------
disp('GetTwoSpectra -> Computing cross & auto spectra for all stacks....');

WI = hanning(block);

start=0;
st = start*block + 1;
en = (start+1)*block;


SPMatrix = zeros([nfrq len nchannel nchannel]);

stack = 1;
for i = (start+1):len,

% FFT, calibration etc.


for u = 1:nchannel,
   K = CorTre(TS.matrix(st:en,u),0);
	Channel1(:,u) = fft(K.*WI);
   Channel(:,Array(u)) = Channel1(2:(block/2)+1,u).*conj(CalData(u,1:block/2)'); %
end; 	
% OOOPS the ' transpose made all the probelm. Solved it with another conj -30,10,02 (b'day eve)
% auto and cross spectra---------------------------
for ii = 1:nfrq,
   par = parzen(TLRad1(ii));
   SPMatrix(ii,stack,:,:) = CompuSPM(Channel,par,TLine1(ii),TLRad1(ii));
end;
%------------------------------------------------
%clear Channel;

st = en + 1;
en = (i+1)*block;
stack=stack+1;
end;
